<template>
  <div class="adg-main">
    <el-form ref="form" :model="infoForm" label-width="120px" :rules="infoRules">
      <el-form-item label="商品分类" prop="category_id">
        <el-select class="el-select-class" v-model="infoForm.category_id" placeholder="选择型号分类" @change="changeCategory">
          <el-option v-for="item in categoryList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品图片" v-if="infoForm.list_pic_url" class="image-uploader-diy new-height">
        <div class="index-image">
          <el-image :preview-src-list="previewList" v-if="infoForm.list_pic_url" :src="infoForm.list_pic_url" @click="previewIndexImg"
            class="image-show" fit="cover"></el-image>
          <div class="o-shadow" @click="delePicList">
            <i class="el-icon-delete"></i>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="商品图片" prop="list_pic_url" v-if="!infoForm.list_pic_url">
        <el-upload name="file" ref="upload" class="upload-demo" :action="uploadImgToQiNiuUrl" :on-success="goodsPicUploadSuccess"
          :auto-upload="true" list-type="picture-card">
          <el-button size="small" type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件</div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品轮播图" prop="goods_sn">
        <draggable v-model="gallery_list" draggable=".gallery-item" class="drag-wrap">
          <div v-for="(element, index) in gallery_list" class="gallery-item" >
            <div v-if="element.is_delete == 0">
              <el-image :preview-src-list="previewList" @click="previewImg(index)" style="width: 148px; height: 148px;margin:0 10px 10px 0;"
                :src="element.url" fit="cover"></el-image>
              <div class="shadow" @click="onRemoveHandler(index)">
                <i class="el-icon-delete"></i>
              </div>
            </div>
          </div>
          <el-upload name="file" ref="uploadGallery"  class="upload-demo" :action="uploadImgToQiNiuUrl"
            :on-success="galleryUploadSuccess" :show-file-list="false" :auto-upload="true" multiple list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </draggable>
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="infoForm.name" @change="changeGoodsName"></el-input>
      </el-form-item>
      <el-form-item label="商品简介" prop="goods_brief">
        <el-input type="textarea" v-model="infoForm.goods_brief" :rows="3"></el-input>
        <div class="form-tip"></div>
      </el-form-item>
      <el-form-item label="商品单位" prop="goods_unit">
        <el-input v-model="infoForm.goods_unit"></el-input>
        <div class="form-tip">如：件、包、袋</div>
      </el-form-item>
      <el-form-item label="销量" prop="sell_volume">
        <el-input v-model="infoForm.sell_volume"></el-input>
      </el-form-item>
      <el-form-item label="型号和价格">
        <div>
          <el-select class="el-select-class" v-model="specValue" placeholder="选择型号分类"  @change="changeSpecValue">
            <el-option v-for="item in specOptionsList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="spec-wrap">
          <el-table :data="specData" stripe size="medium" fit style="width:600px">
            <el-table-column prop="goods_sn" label="商品SKU" width="140">
              <template #default="scope">
                <el-input size="mini"  v-model="scope.row.goods_sn" placeholder="商品SKU"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="goods_aka" label="快递单上的简称" width="160">
              <template #default="scope">
                <el-input @blur="checkSkuOnly(scope.$index, scope.row)" size="mini" v-model="scope.row.goods_name" placeholder="简称"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="型号/规格" width="130">
              <template #default="scope">
                <el-input size="mini" v-model="scope.row.spec_value" placeholder="如1斤/条"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="cost" label="成本(元)" width="100">
              <template #default="scope">
                <el-input size="mini" v-model="scope.row.cost" placeholder="成本"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="retail_price" label="零售(元)" width="100">
              <template #default="scope">
                <el-input size="mini" v-model="scope.row.retail_price" placeholder="零售"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="goods_weight" label="重量(KG)" width="100">
              <template #default="scope">
                <el-input size="mini" v-model="scope.row.goods_weight" placeholder="重量"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="goods_number" label="库存" width="100">
              <template #default="scope">
                <el-input size="mini" v-model="scope.row.goods_number" placeholder="库存"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="70">
              <template #default="scope">
                <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="specDelete(scope.$index, scope.row)">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button class="marginTop20" type="primary" size="small" @click="addSpecData">新增型号</el-button>
        </div>
      </el-form-item>
      <el-form-item label="属性设置" class="checkbox-wrap">
        <el-checkbox label="新品" name="is_new"  v-model="infoForm.is_new" :true-label="1" :false-label="0"></el-checkbox>
      </el-form-item>
      <el-form-item label="选择快递模板">
        <el-select v-model="kdValue" placeholder="请选择快递" @change="kdChange">
          <el-option v-for="item in kdOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort_order">
        <el-input-number :mini="1" :max="100" v-model="infoForm.sort_order"></el-input-number>
      </el-form-item>
      <el-form-item label="">
        <el-switch active-text="上架" inactive-text="下架" :active-value="1" :inactive-value="0" v-model="infoForm.is_on_sale"></el-switch>
      </el-form-item>
      <el-form-item label="商品详情" prop="goods_desc">
        <div class="edit_container">
          <!-- <quill-editor ref="myTextEditor" class="editer"></quill-editor> -->
          <iTinymce :value="this.infoForm.goods_desc" @input="tinyMceInput"></iTinymce>
        </div>
      </el-form-item>

      <!-- 图片上传组件辅助-->
      <el-form-item class="upload_ad">
        <el-upload ref="upload" name="file" class="avatar-uploader" :action="uploadImgToQiNiuUrl" list-type="picture-card"
          :file-list="detail_list"  :on-success="detailUploadSuccess" :data="picData" multiple
          >
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmitInfo" size="small">确定保存</el-button>
        <el-button @click="goBackPage" size="small">返回列表</el-button>
        <el-button type="danger" class="float-right" @click="onCopyGood" v-if="infoForm.id > 0" size="small">复制商品</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible" size="tiny">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
  </div>
</template>
<script>
import { uploadImgToQiNiuUrl }  from '@/api/common.js'
import { getFreightTemplateList }  from '@/api/shipper.js'
import { addGoods }  from '@/api/goods.js'
import { getCategoryList, getSpecList ,checkSku} from '@/api/product'
import iTinymce from '@/components/iTinymce.vue'
import md5 from 'md5'
import { getGoodsById }  from '@/api/goods.js'


export default {
  data(){
    return {
      uploadImgToQiNiuUrl,
      infoForm:{
        name: "",
        list_pic_url: '',
        goods_brief: '',
        goods_desc: '',
        is_on_sale: 1,
        is_new: 0,
        sort_order:1,
      },
      categoryList:[], // 商品分类
      infoRules: {
        category_id:[{
          required: true,
          message: '请选择分类',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }, ],
        goods_brief: [{
          required: true,
          message: '请输入简介',
          trigger: 'blur'
        }, ],
        list_pic_url: [{
          required: true,
          message: '请选择商品图片',
          trigger: 'blur'
        }, ],
      },
      // goodsFileList:[],
      gallery_list:[], // 轮播图
      previewList:['http://boyashop.boya888.xyz/163472739899074569612.png'], // 预览图列表  必须有一张默认的图，为空的话，预览图片需要点击两次才能预览
      specOptionsList:[],
      specData:[
        {
					goods_sn: '',  // sku 生成规则 
					value: '',
					cost: '',
					retail_price: '',
					goods_weight: '',
					goods_number: ''
				}
      ],
      kdValue:'', // 快递
      kdOptions:[],// 快递类型
      detail_list:[] , // 详情图片列表
      dialogVisible:false,
      dialogImageUrl:'',
      specValue:'',
      editType:'create',  // 
      
    }
  },
  async created(){
    let id = this.$route.query.id;
    if(id){
      this.infoForm.id  = id
      this.editType = 'update'
    }else {
      this.editType = 'create'
    }
    this.init()
    // 回显相关逻辑
    if(this.infoForm.id){
      this.feedBack(id)
    }
  },
  components:{
    iTinymce
  },
  methods:{
    async init(){
      // 获取商品分类
      let categoryRes = await getCategoryList()
      if(categoryRes.code === 0){
        this.categoryList = categoryRes.data.map(item=>{
          return {
            label:item.name,
            value:item.id
          }
        })
      }
      // 获取型号和规格
      let specRes = await getSpecList()
      if(specRes.code === 0){
        this.specOptionsList = specRes.data.map(item =>{
          return {
            value:item.id,
            label:item.name
          }
        })
      }
      // 获取快递模板
      let kdRes = await getFreightTemplateList()
      if(kdRes.code === 0){
        this.kdOptions = kdRes.data.map(item=>{
          return {
            value:item.id,
            label:item.name
          }
        })
      }
      
    },
    async feedBack(id){
      let res = await getGoodsById({id})
      if(res.code === 0){
        this.infoForm = res.data
        this.gallery_list = res.data.gallery.map(item=>{
          return {
            id:item.id,
            url:item.img_url,
            is_delete:item.is_delete
          }
        })
        this.specData = res.data.product
        this.specValue = +res.data.specification_id
        this.kdValue = res.data.freight_template_id
      }else {
        this.$message({
          type:'error',
          message:'该商品不存在'
        })
      }
    },

    tinyMceInput(value){
      this.infoForm.goods_desc = value
    },
    // 生成sku
    createSku(index){
      // sku生成规则，分类id + md5(商品名称)前4位+型号规格id+index
      let sku = this.infoForm.category_id + md5(this.infoForm.name).slice(0,4) + this.specValue + index
      return sku
    },
    changeSku(){
      this.specData.forEach((item,index)=>{
        item.goods_sn = this.createSku(index)
      })
    },
    changeCategory(){
      // 改变分类
      this.changeSku()
    },
    changeSpecValue(value){
      // console.log('changeSpecValue value：',value)

      this.specValue = value
      // 改变型号
      this.changeSku()
    },
    changeGoodsName(){
      this.changeSku()
    },
    previewIndexImg() {
      let that = this;
      that.previewList = [];
      that.previewList.push(that.infoForm.list_pic_url);
    },
    delePicList() {
      let that = this;
      that.$confirm('确定删除该图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.infoForm.list_pic_url = '';
        })
        .catch(() => {})
    },
    previewImg(index){
    
      // 图片预览
      this.previewList = []
      this.previewList.push(this.gallery_list[index].url)
    },
    onRemoveHandler(index){
      // 删除某个图片
      let that = this
      that.$confirm('确定删除该图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        that.gallery_list[index].is_delete = 1
      })
      .catch(() => {})
      
    },
    async checkSkuOnly(index,row){
      // 检查sku是否唯一
      if (row.goods_sn === '') {
        this.$message({
          type: 'error',
          message: 'SKU不能为空'
        })
        return false;
      }

      let res = await checkSku({
        goods_sn:row.goods_sn
      })
      if(res.code === 0){
        console.log('res:',res)
        // 根据sku查询商品
        if(res.data.length > 0){
          this.$message({
            type:'error',
            message:'该sku已存在'
          })
        }else{
          this.$message({
            type:'success',
            message:'该sku可用'
          })
        }
      }else{
        this.$message({
          type:'error',
          message:'查询sku失败'
        })
      }
    },
    specDelete(index,row){
      this.specData.splice(index,1)
    },
    goodsPicUploadSuccess(response, file, fileList){
      // console.log('response:',response)
      // console.log('file:',file)
      // console.log('fileList:',fileList)
      if(response.code === 0){
          this.infoForm.list_pic_url = response.data.url
      }
      // this.goodsFileList=[
      //   {
      //     name:file.name,
      //     url:response.data.url
      //   }
      // ]
      this.$refs.form.clearValidate('list_pic_url')
    },
    galleryUploadSuccess(response, file, fileList){
      if(response.code === 0){
          this.gallery_list.push({
            url:response.data.url,
            is_delete: 0,
          })
      }
    },
    addSpecData(){
      // 添加商品型号
      this.specData.push({
					goods_sn: '',
					value: '',
					cost: '',
					retail_price: '',
					goods_weight: '',
					goods_number: ''
				})
    },
    kdChange(){
      // 修改快递
      this.infoForm.freight_template_id = this.kdValue;

    },
    onEditorBlur(){

    },
    onEditorReady(){

    },
    detailUploadSuccess(){
      // 详情图片上传成功
    },
    onSubmitInfo(){
      console.log('this.specValue:',this.specValue)
      // 保存商品
      this.$refs.form.validate(async (valid)=>{
        if(valid){
          // 验证通过
          if(this.gallery_list.length === 0){
            this.$message({
              type:'error',
              message:'请至少上传一张轮播图'
            })
            return false
          }
          if(this.specValue === ''){
            this.$message({
              type:'error',
              message:'规格和型号不能为空'
            })
            return false
          }
          // 对规格和型号进行验证
          for(let i = 0; i < this.specData.length; i++ ){
            let ele = this.specData[i]
            if(ele.cost == '' || ele.goods_sn == '' || ele.goods_weight == '' || ele.retail_price == '' || ele.value ==
								''){
              this.$message({
                type:'error',
                message:'型号和价格不能为空'
              })
              return false
            }
          }

          if(this.editType === 'create'){
            delete this.infoForm.id
          }

          // 轮播图  
          this.infoForm.gallery = this.gallery_list;

          // console.log('this.infoForm:',this.infoForm)
          let data = {
            info: this.infoForm,
            specData: this.specData,  // 规格和价格
            specValue: this.specValue, // 型号分类
          }

          let res = await addGoods(data)
          if(res.code === 0){
            this.$message({
              type:'success',
              message:'新增成功'
            })
            // this.$refs.form.resetFields()
          }else{
            this.$message({
              type:'error',
              message:'新增失败'
            })
          }
        }
      })

    },
    goBackPage(){
      this.$route.push('/product/list')
    },
    onCopyGood(){

    }
  }
}
</script>

<style lang="scss" scoped>
  .adg-main{
    width: 800px;
    background: white;
    ::v-deep .el-form-item__content{
      text-align: left;
    }
    .el-form-item{
      margin-bottom: 30px;
    }
    .spec-wrap{
      margin-top:30px;
    }
    .marginTop20{
      margin-top:20px;
    }
    .upload_ad {
      display: none;
    }
    .upload_ad .el-upload--picture-card {
      display: none;
    }
    .index-image{
      width: 148px;
      height: 148px;
      position: relative;
    }
    .image-show{
      min-width: 148px;
      height: 148px;
      background-color: #f9f9f9;
      display: block;
    }
    .shadow,
    .o-shadow {
      position: absolute;
      bottom: 10px;
      right: 10px;
      background-color: rgba(0, 0, 0, .5);
      opacity: 0;
      transition: opacity .3s;
      color: #fff;
      font-size: 20px;
      line-height: 20px;
      padding: 10px;
      cursor: pointer;
    }

    .gallery-item {
      display: flex;
      justify-content: center;
      align-items: center;
      float: left;
      position: relative;
    }

    .gallery-item:hover .shadow {
      opacity: 1;
    }

    .video-wrap {
      width: 300px;
    }

    .dialog-header {
      display: flex;
      justify-content: flex-start;
      margin-bottom: 10px;
    }

    .dialog-header .value {
      width: 150px;
      margin-right: 14px;
    }

    .input-wrap .el-input {
      width: 200px;
      float: left;
      margin: 0 20px 20px 0;
    }

    .input-wrap .el-input input {
      background-color: #fff !important;
      color: #233445 !important;
    }

    .specFormDialig .el-input {
      width: 150px;
      margin-right: 10px;
    }

    .el-select-class {
      width: 200px;
      margin-right: 20px;
    }

    .sepc-form {
      display: flex;
      justify-content: flex-start;
      margin-bottom: 10px;
    }

    .spec-form-wrap {
      margin-top: 0 !important;
    }

    .add-spec {
      margin-top: 10px;
    }

    .spec-form-wrap .header {
      display: flex;
      justify-content: flex-start;
    }

    .spec-form-wrap .header .l {
      width: 200px;
      margin-right: 20px;
    }

    .spec-form-wrap .header .m {
      width: 200px;
      margin-right: 20px;
    }

    .spec-form-wrap .header .m {
      width: 200px;
      margin-right: 20px;
    }

    /*.sepc-form div{*/
    /*margin-left: 0;*/
    /*}*/

    .float-right {
      float: right;
    }

    .sepc-form .el-input {
      width: 200px;
      margin-right: 20px;
    }

    .marginTop20 {
      margin-top: 20px;
    }

    .checkbox-wrap .checkbox-list {
      float: left;
      margin-right: 20px;
    }

    .upload_ad {
      display: none;
    }

    .upload_ad .el-upload--picture-card {
      display: none;
    }

    .ql-container {
      min-height: 200px;
      max-height: 400px;
      overflow-y: auto;
    }

    .image-uploader-diy {
      /*height: 200px;*/
      position: relative;
    }

    .image-uploader-diy .el-upload {
      border: 1px solid #d9d9d9;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .image-uploader-diy .el-upload:hover {
      border-color: #20a0ff;
    }

    .image-uploader-diy .image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 200px;
      height: 200px;
      line-height: 200px;
      text-align: center;
    }

    .image-uploader-diy .image-show {
      min-width: 148px;
      height: 148px;
      background-color: #f9f9f9;
      display: block;
    }

    .index-image {
      width: 148px;
      height: 148px;
      position: relative;
    }

    .index-image:hover .o-shadow {
      opacity: 1;
    }

    .image-uploader-diy .new-image-uploader {
      font-size: 28px;
      color: #8c939d;
      width: 165px;
      height: 105px;
      line-height: 105px;
      text-align: center;
    }

    .image-uploader-diy .new-image-uploader .image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 165px;
      height: 105px;
      line-height: 105px;
      text-align: center;
    }

    .image-uploader-diy .new-image-uploader .image-show {
      width: 165px;
      height: 105px;
      display: block;
    }

    .item-url-image-fuzhu .el-input {
      width: 260px;
    }

    .hidden {
      display: none;
    }
  }
  
</style>
